/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package it.univaq.iw.jweb;

import it.univaq.iw.jweb.data.DataAccess;
import it.univaq.iw.jweb.data.Servizio;
import it.univaq.iw.jweb.utils.SecurityHelpers;
import it.univaq.iw.jweb.utils.TemplateManager;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author stefano
 */
public class ModificaFoto extends HttpServlet {

    private TemplateManager tpl;
    private DataAccess da;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);

        da = DataAccess.getInstance();
        tpl = TemplateManager.getInstance(getServletContext());
        tpl.setOutlineTemplate("outline");
        tpl.setDefaultData("author", "Del Vecchio - Bevini - Delfino");
        tpl.setDefaultData("homepage_url", "home");
        tpl.setDefaultData("logged", true);
    }

    private void selezionaServizi (String email) throws ServletException {

        List<Servizio> servizi = da.searchServiziGruppo(da.searchNomeGruppo(email));

        /* preparo i servizi in base allo stato del candidato */
        Iterator<Servizio> it = servizi.iterator();
        while (it.hasNext()) {
            Servizio servizio = it.next();
            if (da.curriculumCompletoByMail(email)) { /* curriculum completato */

                if (servizio.getNome().equalsIgnoreCase("inserisciCurriculum")
                        || (da.hasPreferences(email) && servizio.getNome().equalsIgnoreCase("inserisciPreferenze"))) {

                    it.remove();

                } else if(servizio.getNome().equalsIgnoreCase("inserisciCurriculum")
                        || (!da.hasPreferences(email) && servizio.getNome().equalsIgnoreCase("modificaPreferenze"))) {

                    it.remove();
                }

            } else { /* curriculum incompleto */

                if (servizio.getNome().equalsIgnoreCase("inserisciPreferenze")
                        || servizio.getNome().equalsIgnoreCase("modificaPreferenze")
                        || servizio.getNome().equalsIgnoreCase("modificaCurriculum")
                        || servizio.getNome().equalsIgnoreCase("visualizzaCurriculum")
                        || servizio.getNome().equalsIgnoreCase("eliminaCurriculum")) {

                    it.remove();
                }
            }
        }
        tpl.setDefaultData("servizi", servizi);

    }
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        
        HttpSession s = SecurityHelpers.checkSession(request);
        if (s == null) {

            response.sendRedirect("home");

        } else {

            PrintWriter out = response.getWriter();
            
            try {

                selezionaServizi(s.getAttribute("email").toString());
                Map datamodel = tpl.getDefaultDataModel();

                if (!request.getParameterMap().containsKey("t")) {

                    datamodel.put("messaggio", "Inserisci la nuova foto.");
                    datamodel.put("idCurriculum", da.searchIdCurriculumByMail(s.getAttribute("email").toString()));
                    datamodel.put("action","modificaFoto?t=m");
                    tpl.process("modificaFoto", datamodel, out);
                    out.close();
                    return;

                } else {

                    FileItemFactory factory = new DiskFileItemFactory();
                    ServletFileUpload upload = new ServletFileUpload(factory);
                    List<FileItem> items;
                    try {

                        items = upload.parseRequest(request);
                        Iterator<FileItem> it = items.iterator();
                        String idCurriculum = null;
                        InputStream is = null;

                        while(it.hasNext()) {
                            FileItem item = it.next();

                            if (item.getFieldName().equalsIgnoreCase("idCurriculum")) {

                                idCurriculum = item.getString();
                            }

                            if (item.getFieldName().equalsIgnoreCase("foto")) {

                                if (item.getSize() == 0) {
                                    datamodel.put("errore", "ATTENZIONE: Inserisci la nuova foto.");
                                    datamodel.put("idCurriculum", idCurriculum);
                                    datamodel.put("action","modificaFoto?t=m");
                                    tpl.process("modificaFoto", datamodel, out);
                                    out.close();
                                    return;
                                }

                                if (item.getSize() > 63000) {
                                    datamodel.put("errore", "ATTENZIONE: La foto inserita è troppo grande.(MAX: 64 Kbit)");
                                    datamodel.put("idCurriculum", idCurriculum);
                                    datamodel.put("action","modificaFoto?t=m");
                                    tpl.process("modificaFoto", datamodel, out);
                                    out.close();
                                    return;
                                }

                                is = item.getInputStream();                        
                            }
                        }
                        da.aggiungiFoto(is, idCurriculum);
                        da.completaCurriculum(idCurriculum);


                    } catch (FileUploadException ex) {
                        throw new ServletException("Errore nella modifica delle foto.", ex);
                    }

                    /* visualizzo per prova */
                    response.sendRedirect("home");
                    out.close();
                }

            } finally {

                out.close();
            }
        }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
